import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/image_file.dart';
import '../services/file_service.dart';
import '../services/settings_service.dart';
import '../services/database_service.dart';
import '../services/media_scan_service.dart';
import '../widgets/media_grid.dart';
import '../widgets/filter_panel.dart';
import '../widgets/http_video_test.dart';
import '../widgets/basic_video_test.dart';
import 'media_detail_screen.dart';
import 'settings_screen.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String? _selectedDirectory;
  List<MediaFile> _mediaFiles = [];
  List<MediaFile> _filteredMediaFiles = [];
  bool _isLoading = false;
  bool _isScanning = false;
  String _scanProgress = '';
  int _scannedCount = 0;
  int _totalCount = 0;
  MediaFilter _currentFilter = MediaFilter();
  bool _showFilterPanel = true;
  MediaFile? _selectedMediaFile;
  bool _showMetadataInfo = false;

  @override
  void initState() {
    super.initState();
    _initialize();
  }

  Future<void> _initialize() async {
    await FileService.requestPermissions();
    await _loadDefaultDirectory();
  }

  Future<void> _loadDefaultDirectory() async {
    final directory = await SettingsService.getDefaultDirectory();
    if (directory != null && mounted) {
      setState(() {
        _selectedDirectory = directory;
        _isLoading = true;
      });
      
      await _loadMediaFromDatabase();
    }
  }

  Future<void> _loadMediaFromDatabase() async {
    try {
      // 分别加载照片和视频，包含元数据
      final photosData = await DatabaseService.getPhotosWithMetadata();
      final videosData = await DatabaseService.getVideosWithMetadata();
      
      final photos = photosData.map((data) => MediaFile.fromDatabase(data)).toList();
      final videos = videosData.map((data) => MediaFile.fromDatabase(data)).toList();
      
      final mediaFiles = [...photos, ...videos];
      
      if (mounted) {
        setState(() {
          _mediaFiles = mediaFiles;
          _isLoading = false;
        });
        _applyFilters();
      }
    } catch (e) {
      debugPrint('从数据库加载媒体文件失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _scanDirectory() async {
    if (_selectedDirectory == null || _isScanning) return;

    setState(() {
      _isScanning = true;
      _scanProgress = '准备扫描...';
      _scannedCount = 0;
      _totalCount = 0;
    });

    try {
      final result = await MediaScanService.scanDirectory(
        _selectedDirectory!,
        onProgress: (processed, total, currentFile) {
          if (mounted) {
            setState(() {
              _scannedCount = processed;
              _totalCount = total;
              _scanProgress = '正在扫描: ${currentFile.split('/').last}';
            });
          }
        },
      );

      if (mounted) {
        setState(() {
          _isScanning = false;
          _scanProgress = '';
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(result.toString())),
        );

        // 重新加载媒体文件
        await _loadMediaFromDatabase();
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isScanning = false;
          _scanProgress = '';
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('扫描失败: $e')),
        );
      }
    }
  }

  void _applyFilters() {
    setState(() {
      _filteredMediaFiles = _mediaFiles.where((file) {
        // 媒体类型筛选
        if (!_currentFilter.showImages && file.type == MediaType.image) {
          return false;
        }
        if (!_currentFilter.showVideos && file.type == MediaType.video) {
          return false;
        }

        // 文件扩展名筛选
        if (_currentFilter.selectedExtensions.isNotEmpty &&
            !_currentFilter.selectedExtensions.contains(file.extension)) {
          return false;
        }

        // 照片参数筛选
        if (file.type == MediaType.image) {
          // 焦距筛选
          if (_currentFilter.focalLengthRange != null && file.focalLength != null) {
            if (file.focalLength! < _currentFilter.focalLengthRange!.start ||
                file.focalLength! > _currentFilter.focalLengthRange!.end) {
              return false;
            }
          }

          // 光圈筛选
          if (_currentFilter.apertureRange != null && file.aperture != null) {
            if (file.aperture! < _currentFilter.apertureRange!.start ||
                file.aperture! > _currentFilter.apertureRange!.end) {
              return false;
            }
          }

          // ISO筛选
          if (_currentFilter.isoRange != null && file.iso != null) {
            if (file.iso! < _currentFilter.isoRange!.start ||
                file.iso! > _currentFilter.isoRange!.end) {
              return false;
            }
          }
        }

        // 视频参数筛选
        if (file.type == MediaType.video) {
          // 时长筛选（转换为分钟）
          if (_currentFilter.durationRange != null && file.durationSeconds != null) {
            final durationMinutes = file.durationSeconds! / 60;
            if (durationMinutes < _currentFilter.durationRange!.start ||
                durationMinutes > _currentFilter.durationRange!.end) {
              return false;
            }
          }

          // 分辨率筛选
          if (_currentFilter.selectedResolutions.isNotEmpty && file.height != null) {
            final matchesResolution = _currentFilter.selectedResolutions.any((res) {
              switch (res) {
                case '720p':
                  return file.height! >= 720 && file.height! < 1080;
                case '1080p':
                  return file.height! >= 1080 && file.height! < 2160;
                case '4K':
                  return file.height! >= 2160 && file.height! < 4320;
                case '8K':
                  return file.height! >= 4320;
                default:
                  return false;
              }
            });
            if (!matchesResolution) return false;
          }
        }

        return true;
      }).toList();
    });
  }

  void _onFilterChanged(MediaFilter newFilter) {
    setState(() {
      _currentFilter = newFilter;
    });
    _applyFilters();
  }

  Future<void> _openSettings() async {
    await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const SettingsScreen()),
    );
    // 设置返回后重新加载默认目录和媒体文件
    await _loadDefaultDirectory();
  }

  void _onMediaTap(MediaFile mediaFile, int index) {
    setState(() {
      _selectedMediaFile = mediaFile;
      _showMetadataInfo = true;
    });
  }

  void _onSpaceKeyPressed() {
    if (_selectedMediaFile != null) {
      final displayFiles = _currentFilter.hasActiveFilters ? _filteredMediaFiles : _mediaFiles;
      final index = displayFiles.indexOf(_selectedMediaFile!);
      if (index != -1) {
        _openMediaDetail(_selectedMediaFile!, index);
      }
    }
  }

  void _openMediaDetail(MediaFile mediaFile, int index) {
    final displayFiles = _currentFilter.hasActiveFilters ? _filteredMediaFiles : _mediaFiles;
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MediaDetailScreen(
          mediaFiles: displayFiles,
          initialIndex: index,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardListener(
      focusNode: FocusNode()..requestFocus(),
      autofocus: true,
      onKeyEvent: (KeyEvent event) {
        if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.space) {
          _onSpaceKeyPressed();
        }
      },
      child: Scaffold(
      appBar: AppBar(
        title: const Text('媒体查看器'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: Icon(_showFilterPanel ? Icons.filter_list_off : Icons.filter_list),
            onPressed: () {
              setState(() {
                _showFilterPanel = !_showFilterPanel;
              });
            },
            tooltip: _showFilterPanel ? '隐藏筛选' : '显示筛选',
          ),
          if (_selectedDirectory != null && !_isScanning)
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: _scanDirectory,
              tooltip: '重新扫描',
            ),
          IconButton(
            icon: const Icon(Icons.play_circle),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const HttpVideoTest()),
              );
            },
            tooltip: 'HTTP视频测试',
          ),
          IconButton(
            icon: const Icon(Icons.video_library),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const BasicVideoTest()),
              );
            },
            tooltip: '基础视频测试',
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: _openSettings,
            tooltip: '设置',
          ),
        ],
      ),
      body: Column(
        children: [
          // 目录信息栏
          if (_selectedDirectory != null)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                border: Border(
                  bottom: BorderSide(color: Colors.grey[200]!),
                ),
              ),
              child: Row(
                children: [
                  Icon(Icons.folder, color: Colors.grey[600], size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      _selectedDirectory!.split('/').last,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Colors.grey[700],
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (_currentFilter.hasActiveFilters) ...[
                    Icon(Icons.filter_alt, color: Colors.blue[600], size: 16),
                    const SizedBox(width: 4),
                    Text(
                      '${_filteredMediaFiles.length}/${_mediaFiles.length}',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.blue[600],
                      ),
                    ),
                  ],
                ],
              ),
            ),

          // 元信息显示区域
          if (_showMetadataInfo && _selectedMediaFile != null)
            _buildMetadataInfoBar(),
          
          // 主内容区域
          Expanded(
            child: _buildMainContent(),
          ),
        ],
      ),
      ),
    );
  }

  Widget _buildMainContent() {
    // 加载中状态
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    // 扫描中状态
    if (_isScanning) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const CircularProgressIndicator(),
            const SizedBox(height: 16),
            Text('扫描进度: $_scannedCount / $_totalCount'),
            const SizedBox(height: 8),
            Text(
              _scanProgress,
              style: Theme.of(context).textTheme.bodySmall,
              textAlign: TextAlign.center,
            ),
          ],
        ),
      );
    }

    // 未设置目录状态
    if (_selectedDirectory == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.settings, size: 64, color: Colors.grey),
            const SizedBox(height: 16),
            const Text('请在设置中选择默认目录'),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: _openSettings,
              icon: const Icon(Icons.settings),
              label: const Text('打开设置'),
            ),
          ],
        ),
      );
    }

    // 目录为空状态
    if (_mediaFiles.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.folder_open, size: 64, color: Colors.grey),
            const SizedBox(height: 16),
            const Text('此目录中没有找到媒体文件'),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: _scanDirectory,
              icon: const Icon(Icons.search),
              label: const Text('开始扫描'),
            ),
          ],
        ),
      );
    }

    // 左右布局主界面
    return Row(
      children: [
        // 左侧筛选面板
        if (_showFilterPanel)
          FilterPanel(
            currentFilter: _currentFilter,
            onFilterChanged: _onFilterChanged,
          ),
        
        // 右侧媒体展示区域
        Expanded(
          child: _buildMediaDisplayArea(),
        ),
      ],
    );
  }

  Widget _buildMediaDisplayArea() {
    final displayFiles = _currentFilter.hasActiveFilters ? _filteredMediaFiles : _mediaFiles;
    
    if (displayFiles.isEmpty && _currentFilter.hasActiveFilters) {
      // 筛选后无结果
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.search_off, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text(
              '没有符合筛选条件的文件',
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '尝试调整筛选条件或清除筛选',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      );
    }

    return MediaGrid(
      mediaFiles: displayFiles,
      onMediaTap: _onMediaTap,
      selectedMediaFile: _selectedMediaFile,
    );
  }

  Widget _buildMetadataInfoBar() {
    if (_selectedMediaFile == null) return const SizedBox.shrink();

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        border: Border(
          bottom: BorderSide(color: Colors.blue[200]!),
        ),
      ),
      child: Row(
        children: [
          // 文件图标
          Icon(
            _selectedMediaFile!.type == MediaType.video
                ? Icons.videocam
                : Icons.photo,
            color: Colors.blue[700],
            size: 20,
          ),
          const SizedBox(width: 12),
          
          // 文件信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 文件名
                Text(
                  _selectedMediaFile!.name,
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: Colors.blue[800],
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                
                // 详细元信息
                _buildDetailedMetadata(_selectedMediaFile!),
              ],
            ),
          ),

          // 空格键提示
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(4),
            ),
            child: Text(
              '空格键打开',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[700],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDetailedMetadata(MediaFile mediaFile) {
    if (mediaFile.type == MediaType.image) {
      return _buildPhotoDetailedMetadata(mediaFile);
    } else if (mediaFile.type == MediaType.video) {
      return _buildVideoDetailedMetadata(mediaFile);
    }
    return const SizedBox.shrink();
  }

  Widget _buildPhotoDetailedMetadata(MediaFile mediaFile) {
    final metadataRows = <Widget>[];
    
    // 第一行：基本参数
    final basicInfo = <String>[];
    if (mediaFile.width != null && mediaFile.height != null) {
      basicInfo.add('${mediaFile.width}×${mediaFile.height}');
    }
    if (mediaFile.focalLength != null) {
      basicInfo.add('${mediaFile.focalLength!.toInt()}mm');
    }
    if (mediaFile.aperture != null) {
      basicInfo.add('f/${mediaFile.aperture!.toStringAsFixed(1)}');
    }
    if (mediaFile.iso != null) {
      basicInfo.add('ISO${mediaFile.iso}');
    }
    
    if (basicInfo.isNotEmpty) {
      metadataRows.add(
        Text(
          basicInfo.join(' • '),
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Colors.grey[700],
          ),
        ),
      );
    }

    // 第二行：相机信息和文件信息
    final cameraAndFileInfo = <String>[];
    if (mediaFile.cameraMake != null || mediaFile.cameraModel != null) {
      cameraAndFileInfo.add('${mediaFile.cameraMake ?? ''} ${mediaFile.cameraModel ?? ''}');
    }
    cameraAndFileInfo.add('${_formatFileSize(mediaFile.size)} • ${mediaFile.extension.substring(1).toUpperCase()}');
    
    if (cameraAndFileInfo.isNotEmpty) {
      metadataRows.add(
        Text(
          cameraAndFileInfo.join(' • '),
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Colors.grey[600],
            fontSize: 11,
          ),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: metadataRows.map((widget) => Padding(
        padding: const EdgeInsets.only(bottom: 2),
        child: widget,
      )).toList(),
    );
  }

  Widget _buildVideoDetailedMetadata(MediaFile mediaFile) {
    final metadataRows = <Widget>[];
    
    // 第一行：基本参数
    final basicInfo = <String>[];
    if (mediaFile.width != null && mediaFile.height != null) {
      basicInfo.add('${mediaFile.width}×${mediaFile.height}');
    }
    if (mediaFile.durationSeconds != null) {
      basicInfo.add(_formatDuration(mediaFile.durationSeconds!));
    }
    if (mediaFile.codec != null) {
      basicInfo.add(mediaFile.codec!.toUpperCase());
    }
    
    if (basicInfo.isNotEmpty) {
      metadataRows.add(
        Text(
          basicInfo.join(' • '),
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Colors.grey[700],
          ),
        ),
      );
    }

    // 第二行：文件信息
    final fileInfo = '${_formatFileSize(mediaFile.size)} • ${mediaFile.extension.substring(1).toUpperCase()}';
    metadataRows.add(
      Text(
        fileInfo,
        style: Theme.of(context).textTheme.bodySmall?.copyWith(
          color: Colors.grey[600],
          fontSize: 11,
        ),
      ),
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: metadataRows.map((widget) => Padding(
        padding: const EdgeInsets.only(bottom: 2),
        child: widget,
      )).toList(),
    );
  }

  String _formatDuration(double seconds) {
    final minutes = (seconds / 60).floor();
    final secs = (seconds % 60).floor();
    if (minutes > 60) {
      final hours = (minutes / 60).floor();
      final remainingMinutes = minutes % 60;
      return '$hours:${remainingMinutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
    }
    return '$minutes:${secs.toString().padLeft(2, '0')}';
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '${bytes}B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)}KB';
    if (bytes < 1024 * 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
  }
}